package com.xp.basic.heima.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class TestSelectorNio {

    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8080));
        ssc.configureBlocking(false);

        ssc.register(selector, SelectionKey.OP_ACCEPT);

        while (true){
            System.out.println("  connecting  .....");
            //这里阻塞等待事件发生
            // selector 中的 key 必须处理，要么是 处理了 要么是取消了 反正必须处理
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey next = iterator.next();
                iterator.remove();


                if (next.isAcceptable()) {
                    ServerSocketChannel channel = (ServerSocketChannel) next.channel();
                    SocketChannel sc = channel.accept();
                    System.out.println("sc:"+sc);
                    sc.configureBlocking(false);
                    SelectionKey selectionKey = sc.register(selector, 0, null);
                    selectionKey.interestOps(SelectionKey.OP_READ);

                }else if (next.isReadable()){
                    SocketChannel channel = (SocketChannel) next.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    int read = channel.read(byteBuffer);
                    byte[] bytes = new byte[read];
                    byteBuffer.flip();
                    byteBuffer.get(bytes);
                    String msg = new String(bytes);
                    System.out.println("收到："+channel+"的消息："+msg);
                    byteBuffer.clear();
                }
            }
        }

    }
}
